package com.xhwl.centiotdata.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhwl.centiotdata.dao.ICampusUserStatisticsDao;
import com.xhwl.centiotdata.pojo.constant.BaiLianConstant;
import com.xhwl.centiotdata.service.integrateconfig.IntegrationConfig;
import com.xhwl.centiotdata.suppliersystem.bailian.CompanyBaiLianHandler;
import com.xhwl.centiotdata.suppliersystem.bailian.GeneralBaiLianHandler;
import com.xhwl.centiotdata.suppliersystem.bailian.SaleBaiLianHandler;
import com.xhwl.centiotdata.suppliersystem.eesd.batown.BaApiHandler;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.common.vo.cent.statistics.SaleThirdDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 18:46 2021/1/14
 */
@RestController
@Slf4j
public class SaleController {

    @Autowired
    BaApiHandler baApiHandler;

    @Autowired
    SaleBaiLianHandler saleBaiLianHandler;

    @Autowired
    private GeneralBaiLianHandler generalBaiLianHandler;

    private static String IP_AND_PORT = "http://172.50.57.20";

    private static Integer PROJECT_ID = 1;
    @Autowired
    ICampusUserStatisticsDao iCampusUserStatisticsDao;

    @Autowired
    private CompanyBaiLianHandler companyBaiLianHandler;

    /**
     * 立即同步店铺数据
     */
    @RequestMapping(value = "/sale/company")
    public void syncCompany() {
        companyBaiLianHandler.syncCompany(PROJECT_ID, IP_AND_PORT);
    }


    /**
     * 立即同步店铺数据
     *
     * @param projectId
     */
    @RequestMapping(value = "/sale/company/sync/new")
    public void syncCompanyNew(Integer projectId, boolean clearHistoryCategory) {
        IntegrationConfig.integrationConfigList.stream()
                .filter(integrationConfig -> integrationConfig.getProductId().intValue() == 9 && integrationConfig.getProdCategoryId() == null)
                .forEach(config -> {
                    if (Objects.equals(config.getProjectId(), projectId)) {
                        JSONObject properties = config.getProperties();
                        String ipAndPort = properties.getString("ipAndPort");
                        companyBaiLianHandler.syncCompany(projectId, ipAndPort, clearHistoryCategory);
                    }
                });
    }

    /**
     * 立即拉取昨日数据
     */
    @RequestMapping(value = "/sale/index")
    public void index() {
        saleBaiLianHandler.pullSalesYesterday(PROJECT_ID, IP_AND_PORT);
    }

    /**
     * 立即拉取今日数据
     */
    @RequestMapping(value = "/sale/index/today")
    public void indexToday() {
        saleBaiLianHandler.pullSalesToday(PROJECT_ID, IP_AND_PORT);
    }

    /**
     * 销售额补救 - 更新昨天或者某一天的数据
     * 不可使用，该接口已停止维护
     */
    @Deprecated
    @RequestMapping(value = "/sale/old")
    public void saleInsert(String date) throws Exception {
        //删除dwd_fact_operation_sale_record date:00:05:00 date 到 date+1:00:05:00
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date format = sdf1.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(format);
        calendar.add(Calendar.DAY_OF_MONTH, +1);
        String format1 = sdf1.format(calendar.getTime());
        String startTime = date + " 00:05:00";
        String endTime = format1 + " 00:05:00";
        iCampusUserStatisticsDao.deleteTimeByBetweenTime(startTime, endTime);
        pullSale(date);
    }

    /**
     * 销售补救 - v2
     *
     * @param date
     */
    @RequestMapping(value = "/sale/v2/history")
    public void saleHistory(int projectId, String ipAndPort, int type, String date) {
        if (StringUtils.isEmpty(ipAndPort)) {
            ipAndPort = IP_AND_PORT;
        }
        switch (type) {
            case 0:
                //拉取指定日期
                saleBaiLianHandler.pullSales(projectId, ipAndPort, date);
                return;
            case 1:
                saleBaiLianHandler.pullSalesDays(projectId, ipAndPort, Integer.parseInt(date));
                return;
        }

    }

    @Deprecated
    public void pullSale(String date) {
        List<SaleThirdDataVO> records = getUrlData(date);
        Date nowTime = new Date();
        List<Map<String, Object>> maps = Lists.newArrayList();
        String[] split = date.split("-");
        for (SaleThirdDataVO record : records) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("project_id", PROJECT_ID);
            map.put("year", split[0]);
            map.put("month", split[1]);
            map.put("day", split[2]);
            map.put("value", record.getSales());
            map.put("current_value", record.getSales());
            map.put("prev_value", 0);
            map.put("count", record.getCount());
            map.put("prev_count", 0);
            map.put("current_count", record.getCount());
            map.put("sales_type", record.getSalesType());
            map.put("shop_id", record.getDepartmentID());
            Map<String, Object> shop = iCampusUserStatisticsDao.findShop(record.getDepartmentID());
            map.put("shop_name", ChkUtil.isNull(shop) ? "" : shop.get("name"));
            map.put("shop_type", ChkUtil.isNull(shop) ? "" : shop.get("type"));
            //赋值供应货物品类
            map.put("supplier_category_code", ChkUtil.isNull(shop) ? "" : shop.get("supplier_category_code"));
            //赋值销售员信息
//            map.put("seller_no", record.getNo());
//            map.put("seller_name", record.getName());
            map.put("event_time", date + " 23:51:00");
            map.put("created_at", nowTime);
            maps.add(map);
        }
        iCampusUserStatisticsDao.insertSaleRecord(maps);
    }

    private List<SaleThirdDataVO> getUrlData(String date) {
        HashMap<String, Object> params = Maps.newHashMap();
        if (ChkUtil.isNotNull(date)) {
            params.put("date", date);
        }
        JSONObject resultObject = generalBaiLianHandler.post(IP_AND_PORT + BaiLianConstant.SALES_URL, params);
        String data = resultObject.getString("data");
        if (StringUtils.isEmpty(data)) {
            log.error("post path:{};params:{}; data is null !", IP_AND_PORT + BaiLianConstant.SALES_URL, JSON.toJSONString(params));
            return null;
        }
        List<SaleThirdDataVO> records = JSONObject.parseArray(data, SaleThirdDataVO.class);
        return records;
    }


    /**
     * 当日销售额实时统计
     */
    @RequestMapping(value = "/sale/today")
    public List<SaleThirdDataVO> getStrameSaleData() {
        IntegrationConfig.integrationConfigList.stream()
                .filter(integrationConfig -> integrationConfig.getProductId() == 9 && integrationConfig.getProdCategoryId() == null)
                .forEach(integrationConfig -> {
                    try {
                        JSONObject properties = integrationConfig.getProperties();
                        IP_AND_PORT = properties.getString("ipAndPort");
                        PROJECT_ID = integrationConfig.getProjectId();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
        return getUrlData(null);
    }
}
